import Vue from 'vue'
import router from '@/router'
import { getToken, setToken, removeToken, setSecretToken, getSecretToken, removeSecretToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { message } from 'ant-design-vue'
import {
    loginAPI,
    registerAPI,
    getUserInfoAPI,
    updateUserInfoAPI,
    investCreditAPI,
    creditAPI,
    addCommentAPI,
    getuserpicAPI,
    registeredmemberAPI
} from '@/api/user'

import {
    getUserOrdersAPI,
    cancelOrderAPI,
} from '@/api/order'
import {logoutAPI} from "../../api/user";

const user = {
    state : {
        userId: '',
        creditInfo:[],
        userInfo: {
        },
// 要求加上 memberType：string 和isMember：bool
        userOrderList: [],
        registeredMemberVisible: false,
        userCommentVisible:false,
        token: "",
        adduserimgVisible:false,
        userpic:{}
    },
    mutations: {
        reset_state: function(state) {
            state.token = '';
            state.userId = '';
            state.userInfo = {

            };
            state.creditData=[];
            state.userOrderList = [];
        },
        //改变注册会员是否显示
        set_registeredMemberVisible: function(state, data) {
            state.registeredMemberVisible = data
        },
        set_token: function(state, token){
            state.token = token
        },
        set_email: (state, data) => {
            state.email = data
        },
        set_userId: (state, data) => {
            state.userId = data
        },
        set_userInfo: (state, data) => {
            state.userInfo = {
                ...state.userInfo,
                ...data
            }
        },
        set_userCommentVisible:(state, data) => {
            state.userCommentVisible = data
        },
        set_userOrderList: (state, data) => {
            state.userOrderList = data
        },
        set_creditInfo: (state, data) => {
            state.creditInfo = data
        },
        set_adduserimgVisible: (state, data) => {
            state.adduserimgVisible = data
        },
        set_userpic:(state, data) => {
            state.userpic = data
        },
    },

    actions: {
        login: async ({ dispatch, commit }, userData) => {
            const res = await loginAPI(userData)
            if(res){
                setToken(res.id)
                setSecretToken(res.token)
                localStorage.setItem("token", res.token)
                commit('set_userId', res.id)
                dispatch('getUserInfo')
                if(res.userType=='Admin'){
                    router.push('/admin/manageUser')
                }
                else
                router.push('/hotel/hotelList')
            }
            else{
                message.error('用户名或密码错误！')
            }
        },
        register: async({ commit }, data) => {
            const res = await registerAPI(data)
            if(res){
                message.success('注册成功')
            }
        },
        getUserInfo({ state, commit }) {
            // console.log('diaoyongl')
            return new Promise((resolve, reject) => {
              getUserInfoAPI(state.userId).then(response => {
                const data = response
                if (!data) {
                  reject('登录已过期，请重新登录')
                }
                commit('set_userInfo', data)
                commit('set_userId', data.id)
                resolve(data)
              }).catch(error => {
                reject(error)
              })
            })
        },
        updateUserInfo: async({ state, dispatch }, data) => {
            const params = {
                id: state.userId,
                ...data,
            }
            const res = await updateUserInfoAPI(params)
            if(res){
                message.success('修改成功')
                dispatch('getUserInfo')
            }
        },
        getuserpic: async({ state, commit}, data) => {

            const res = await getuserpicAPI(data)
            if (res) {
                commit('set_userpic', res)
            }else {
                var pic={
                    pic:null
                }
                commit('set_userpic', pic)
            }

        },
        addComment: async({ state, commit }, data) => {

            const res = await addCommentAPI(data)
            // if(res){
            commit('set_userCommentVisible', false)
            message.success('评论成功')
            // }else {
            //     // commit('set_userCommentVisible', true)
            //     message.error('评论失败')
            // }
        },
        getUserOrders: async({ state, commit }) => {
            const data = {
                userId: Number(state.userId)
            }
            const res = await getUserOrdersAPI(data)
            if(res){
                commit('set_userOrderList', res)
            }
        },
        getCreditInfo: async({ state, commit }) => {
            const data = {
                userId: Number(state.userId)
            }
            const res = await creditAPI(data.userId)
            if(res){
                commit('set_creditInfo', res)
            }
        },

        cancelOrder: async({ state, dispatch }, orderId) => {
            const res = await cancelOrderAPI(orderId)
            console.log(res)
            if(res) {
                dispatch('getUserOrders')
                message.success('撤销成功')
            }else{
                message.error('撤销失败')
            }
        },
        logout: async({ commit }) => {
            removeToken()
            removeSecretToken()
            commit('reset_state')
            resetRouter()
            const res = await logoutAPI();
        },
          // remove token
        resetToken({ commit }) {
            return new Promise(resolve => {
                removeToken() // must remove  token  first
                commit('reset_state')
                resolve()
            })
        },
        investCredit: async({ state, dispatch }, data) => {
            const res = await investCreditAPI(data)
            if(res) {
                dispatch('getCreditInfo')
                message.success('充值成功')
            }else{
                message.error('充值失败')
            }
        },
        registeredmember: async({ state, dispatch }, data) => {
            const res = await registeredmemberAPI(data)
            if(res) {
                dispatch('getCreditInfo')
                message.success('注册会员成功')
            }else{
                message.error('绑定会员失败')
            }
        },
    }
}

export default user
